package com.haifeng.lyw.blerobot.custom;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.haifeng.lyw.blerobot.R;
import com.haifeng.lyw.blerobot.utils.L;



public class DragViewCtr {
    private static final int MOVE_LENGH = 150;

    private int screenHeight;
    private int screenWidth;
    private int viewWidth;
    private int viewHeight;
    /**
     * 被拖动的图
     */
    private ImageButton iv_drag;
    private SharedPreferences sp;
    private Activity activity;

    private boolean isCanDrag = true;

    public void setCanDrag(boolean canDrag) {
        isCanDrag = canDrag;
    }

    private OnClickListener onClickListener;

    public interface OnClickListener{
        void onClick();
    }
    public void setOnClickListener(OnClickListener onClickListener){
        this.onClickListener = onClickListener;
    }

    public DragViewCtr(Activity activity) {
        this.activity = activity;
        this.screenHeight = activity.getWindowManager().getDefaultDisplay()
                .getHeight();
        this.screenWidth = activity.getWindowManager().getDefaultDisplay()
                .getWidth();

        ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
        LayoutInflater factory = LayoutInflater.from(activity);
        View layout = factory.inflate(R.layout.custom_drag, null);
        decorView.addView(layout);
        viewWidth = layout.getWidth();
        viewHeight = layout.getHeight();
        this.iv_drag = (ImageButton) layout.findViewById(R.id.startBtn);
        this.sp = activity.getSharedPreferences("config", Context.MODE_PRIVATE);
    }
    /**
     * 显示可拖动的图标
     */
    public void showDragCallView() {

        this.iv_drag.setVisibility(View.VISIBLE);
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels; // 屏幕宽度（像素）
        int height = metric.heightPixels; // 屏幕高度（像素）
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        iv_drag.measure(w, h);
        int viewheight =iv_drag.getMeasuredHeight();
        int viewwidth =iv_drag.getMeasuredWidth();
        int lastx = this.sp.getInt("lastx", width-viewwidth-30);
        int lasty = this.sp.getInt("lasty", height-viewheight-50);

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) this.iv_drag
                .getLayoutParams();
        params.leftMargin = lastx;
        params.topMargin = lasty;
        this.iv_drag.setLayoutParams(params);

        this.iv_drag.setOnTouchListener(new View.OnTouchListener() {
            int startX;
            int startY;
            long downTime;
            long upTime;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!isCanDrag)
                    return true;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:// 手指第一次触摸到屏幕
//                        iv_drag.setBackgroundResource(R.drawable.setting_cusromer_drag_down);
                        this.startX = (int) event.getRawX();
                        this.startY = (int) event.getRawY();
                        downTime = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_MOVE:// 手指移动
                        //当前的位置 x,y
                        int newX = (int) event.getRawX();
                        int newY = (int) event.getRawY();

                        //计算出手指移动的位置的 x,y
                        int dx = newX - this.startX;
                        int dy = newY - this.startY;

                        // 计算出来控件原来的位置
                        int l = iv_drag.getLeft();
                        int r = iv_drag.getRight();
                        int t = iv_drag.getTop();
                        int b = iv_drag.getBottom();

                        //计算控件的新位置
                        int newt = t + dy;
                        int newb = b + dy;
                        int newl = l + dx;
                        int newr = r + dx;

                        if ((newl < 0) || (newt < 0) || (newr > screenWidth)
                                || (newb > screenHeight)) {
                            break;
                        }

                        // 更新iv在屏幕的位置.
                        iv_drag.layout(newl, newt, newr, newb);
                        this.startX = (int) event.getRawX();
                        this.startY = (int) event.getRawY();

                        break;
                    case MotionEvent.ACTION_UP: // 手指离开屏幕的一瞬间
                        int lastx = iv_drag.getLeft();
                        int lasty = iv_drag.getTop();
                        int ivHeight = iv_drag.getHeight();

                        upTime = System.currentTimeMillis();
                        L.e("startX", "" + startX);
                        L.e("startY", "" + startY);
                        L.e("lastx", "" + lastx);
                        L.e("lasty", "" + lasty);
                        if (Math.abs(lastx - startX) < MOVE_LENGH
                                && Math.abs(lasty - startY) < MOVE_LENGH
                                && (upTime - downTime) < 150l) {
                            //点击操作
                            L.i("click","悬浮按钮-点击");
                            if (onClickListener != null)
                                onClickListener.onClick();
                        }else {
                            int dx1 = (int) event.getRawX() - lastx;
                            int dy1 = (int) event.getRawY() - lasty;
                            int left1 = iv_drag.getLeft() + dx1;
                            int top1 = iv_drag.getTop() + dy1;
                            int right1 = iv_drag.getRight() + dx1;
                            int bottom1 = iv_drag.getBottom() + dy1;
                            if (left1 < (screenWidth / 2)) {
                                if (top1 < 100) {
                                    iv_drag.layout(left1, 0, right1, ivHeight);
                                } else if (bottom1 > (screenHeight - 200)) {
                                    iv_drag.layout(left1, (screenHeight - ivHeight), right1, screenHeight);
                                } else {
                                    iv_drag.layout(0, top1, ivHeight, bottom1);
                                }
                            } else {
                                if (top1 < 100) {
                                    iv_drag.layout(left1, 0, right1, ivHeight);
                                } else if (bottom1 > (screenHeight - 200)) {
                                    iv_drag.layout(left1, (screenHeight - ivHeight), right1, screenHeight);
                                } else {
                                    iv_drag.layout((screenWidth - ivHeight), top1, screenWidth, bottom1);
                                }
                            }
                        }
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putInt("lastx", lastx);
                        editor.putInt("lasty", lasty);
                        editor.commit();
//                        iv_drag.setBackgroundResource(R.drawable.setting_cusromer_drag);
                        break;
                }
                return true;
            }
        });
    }

    /**
     *
     */
    public void hideDragCallView() {

        this.iv_drag.setVisibility(View.GONE);
    }

}
